<template>
    <el-card shadow="hover" class="industrial-card">
        <!-- 顶部控制区域 -->
        <div class="industrial-control-panel">
            <!-- 原有内容保持不变 -->
            <div class="control-section ">
                <!-- 产线工位选择 -->
                <div class="selection-area">
                    <div class="selection-item">
                        <span class="selection-label">产线：</span>
                        <el-select v-model="selectedMessage.LineCode" placeholder="请选择产线" class="selection-input">
                            <el-option v-for="line in stateInfo.AllLines" :key="line.Text" :value="line.Text" :label="line.Text"></el-option>
                        </el-select>
                    </div>

                    <div class="selection-item">
                        <span class="selection-label">工位：</span>
                        <el-select v-model="selectedMessage.StationCode" placeholder="请选择工站" class="selection-input">
                            <el-option v-for="station in stateInfo.AllStations" :key="station.StationCode" :value="station.StationCode" :label="station.StationCode"></el-option>
                        </el-select>
                        <span class="station-name">{{ StationName }}</span>
                    </div>
                    <div class="selection-item">
                        <span class="selection-label">工艺校验：</span>
                        <el-tag :type="stationStatus === '启用' ? 'success' :
                 stationStatus === '未启用' ? 'danger' :
                'info'">
                            {{ stationStatus }}
                        </el-tag>
                    </div>
                </div>

                <!-- 串口控制 -->
                <div class="serial-control">
                    <el-button type="primary" plain @click="openPort">连接串口</el-button>
                    <el-button type="danger" plain @click="closePort">关闭串口</el-button>
                    <div class="status-indicator" :style="serialColor"></div>
                </div>
            </div>
        </div>


        <!-- 扫码区域 -->
        <div class="scan-section">
            <div class="scan-input-group">
                <el-form-item label="物料条码：" class="scan-item">
                    <el-input v-model="textSN" disabled class="scan-input"></el-input>
                </el-form-item>
                <el-form-item label="扫码结果：" class="scan-item">
                    <el-input v-model="SNMessage" disabled class="scan-input"></el-input>
                </el-form-item>
                <el-form-item label="过站节拍：" class="scan-item">
                    <div class="cycletime-display">{{ CycleTime  }}</div>
                </el-form-item>
                <!-- 特殊工位展示内容 -->
                <el-form-item v-show="selectedMessage.StationCode=='2-OP3010-0'" label="上线模式：" class="scan-item">
                    <div :class="TZanimateClass">{{ TZStationStatus }}</div>
                </el-form-item>
                <el-form-item v-show="selectedMessage.StationCode=='2-OP3250-0'||selectedMessage.StationCode=='2-OP3300-0'" label="涂胶报警：" class="scan-item">
                    <CountdownTimer :seconds="CountDowntimeString" />
                </el-form-item>
                <!-- 移除原有的涂胶状态显示 -->

            </div>
            <div class="sn-display">
                SN: {{ stateInfo.OrderInfo.length == 0 ? '' : stateInfo.OrderInfo[0].SN }}
            </div>
        </div>

        <el-divider class="section-divider" />

        <!-- 功能按钮区域 -->
        <div class="action-buttons">
            <!-- <el-popconfirm title="确定出站吗？" @confirm="ForcePassstation">
                <template #reference>
                    <el-button type="primary" class="action-button">
                        <div class="bilingual-text">
                            <div>强制出站</div>
                            <div>บังคับให้ออกจากสถานี</div>
                        </div>
                    </el-button>
                </template>
            </el-popconfirm> -->

            <el-button v-show="selectedMessage.StationCode=='2-OP4010-1'" type="primary" class="action-button" @click="backUpshowModal=true">
                <div class="bilingual-text">
                    <div>返修上线</div>
                    <div>รีอินไลน์สินค้าซ่อมแล้ว</div>
                </div>
            </el-button>
            <el-button v-show="selectedMessage.StationCode=='2-OP3010-0'" type="primary" class="action-button" @click="TZbackupShowModal=true">
                <div class="bilingual-text">
                    <div>电机返修上线</div>
                    <div>มอเตอร์ซ่อมเข้าไลน์</div>
                </div>
            </el-button>

            <el-button type="primary" class="action-button" @click="supple_materialShowModal=true">
                <div class="bilingual-text">
                    <div>物料补漏</div>
                    <div>การเติมวัสดุที่ขาด</div>
                </div>
            </el-button>

            <!-- 新增涂胶状态按钮 -->
            <el-button v-show="selectedMessage.StationCode=='2-OP3250-0'"
                       :class="['action-button', 'glue-status-action-button', glueTimeoutStatus === 'true' ? 'glue-timeout' : 'glue-normal']"
                       :disabled="glueTimeoutStatus !== 'true'"
                       @click="handleGlueTimeoutButtonClick">
                <div class="bilingual-text">
                    <div>涂胶状态</div>
                    <div>{{ glueTimeoutStatus === 'true' ? '超时' : '正常' }}</div>
                </div>
            </el-button>

            <el-button type="primary" class="action-button" @click="showModal = true">
                <div class="bilingual-text">
                    <div>不良品管理</div>
                    <div>การจัดการของเสีย</div>
                </div>
            </el-button>

            <el-button type="primary" class="action-button" @click="BatchInfoShowModal=true">
                <div class="bilingual-text">
                    <div>批次更换</div>
                    <div>การเปลี่ยนล็อต</div>
                </div>
            </el-button>

            <el-button type="primary" class="action-button" @click="SkipShowModal=true">
                <div class="bilingual-text">
                    <div>跳站管理</div>
                    <div>ข้ามสถานีงาน</div>
                </div>
            </el-button>
        </div>

        <el-divider class="section-divider" />

        <!-- 工单信息 -->
        <div class="order-info">
            <div v-if="stateInfo.OrderInfo.length == 0" class="no-order">暂无工单信息</div>
            <div v-else class="order-details">
                <div class="order-row">
                    <div class="order-item">
                        <span class="order-label">当前工单：</span>
                        <span class="order-value">{{ stateInfo.OrderInfo[0].OrderCode }}</span>
                    </div>
                    <div class="order-item">
                        <span class="order-label">当前排程：</span>
                        <span class="order-value">{{ stateInfo.OrderInfo[0].ScheduleCode }}</span>
                    </div>
                    <div class="order-item">
                        <span class="order-label">产品编码：</span>
                        <span class="order-value">{{ stateInfo.OrderInfo[0].MaterialCode }}</span>
                    </div>
                </div>
                <div class="order-row">
                    <div class="order-item">
                        <span class="order-label">产品名称：</span>
                        <span class="order-value">{{ stateInfo.OrderInfo[0].MaterialName }}</span>
                    </div>
                    <div class="order-item">
                        <span class="order-label">工位产出：</span>
                        <span class="order-value">{{ stateInfo.OrderInfo[0].FinishedCount }}</span>
                    </div>
                    <div class="order-item">
                        <span class="order-label">下线数量：</span>
                        <span class="order-value">{{ stateInfo.OrderInfo[0].FinishedCount }}</span>
                    </div>
                </div>
                <div class="status-message" :class="{'success': alertMessageJudge, 'error': !alertMessageJudge}">
                    {{ alertMessageJudge ? '日志更新成功' : alertMessage }}
                </div>
            </div>
            <div class="comein-indicator" :style="comeinColor">comein</div>
        </div>

        <el-divider class="section-divider" />

        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 物料绑定表格 -->
            <div class="material-table" v-show="stateInfo.AllMaterial.length">
                <el-table :data="stateInfo.AllMaterial"
                          :row-class-name="tableRowClassName"
                          style="width: 100%"
                          :default-expand-all="true"
                          :header-cell-style="{background:'#409EFF', color:'white'}">
                    <el-table-column prop="AssemblyMaterialCode" label="物料编码" width="180" align="center" />
                    <el-table-column prop="AssemblyMaterialName" label="物料名称" width="180" align="center" />
                    <el-table-column label="需装配数量" width="120" align="center">
                        <template v-slot:default="scope">
                            {{ scope.row.AssemblyConsumption.slice(0, -1) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="已装配数量" width="120" align="center">
                        <template v-slot="scope">
                            <span v-if="stateInfo.AllBindings && stateInfo.AllBindings[scope.row.AssemblyMaterialCode]">
                                {{ stateInfo.AllBindings[scope.row.AssemblyMaterialCode].length }}
                            </span>
                            <span v-else>0</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="装配状态" width="120" align="center">
                        <template v-slot="scope">
                            <el-tag :type="scope.row.AssemblyConsumption[scope.row.AssemblyConsumption.length - 1] == '+' ? 'success' : 'info'">
                                {{ scope.row.AssemblyConsumption[scope.row.AssemblyConsumption.length - 1] == '+' ? '完成' : '待装配' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="物料SN" align="center">
                        <template #default="props">
                            <el-table :data="stateInfo.AllBindings[props.row.AssemblyMaterialCode]" style="width: 100%">
                                <el-table-column prop="AssemblyMaterialSn" width="200" align="center" />
                                <el-table-column prop="AssemblyMaterialQty" width="100" align="center" />
                            </el-table>
                        </template>
                    </el-table-column>
                </el-table>
                <div v-show="selectedMessage.StationCode=='2-OP3010-0'">

                    <span :class="['value-box', animateClass]">

                        {{ stateInfo.AllMaterial.length > 0?stateInfo.AllMaterial[0].AssemblyMaterialCode:'' }}
                    </span>

                </div>
            </div>

            <!-- 工位日志 -->
            <div class="log-section">
                <h3 class="log-title">工位日志</h3>
                <div class="log-container">
                    <!-- <div v-for="item in stateInfo.AllLogs" :key="item.Date_Time" class="log-item" :class="{'error-log': item.LogType !== 'good'}">
                  <span class="log-time">{{ item.Date_Time }}</span>
                  <span class="log-content">{{ item.Log }}</span>
                </div> -->
                    <ul class="log-item" v-for="item in stateInfo.AllLogs">
                        <li v-if="item.LogType=='good'" style="color: black;font-size: 16px;">{{ item.Date_Time }}: {{ item.Log }}</li>
                        <li v-else style="color: red;font-size: 16px;">{{ item.Date_Time }}: {{ item.Log }}</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- 弹窗组件（保持原有内容不变） -->
        <!-- 返修弹窗 -->
        <el-dialog v-model="backUpshowModal" title="返修管理" width="50%" center>
            <div class="repair-box">
                <el-button type="primary" @click="ChangeRepairStationStatus('repair')">
                    <div class="bilingual-text">
                        <div>返修件上线</div>
                        <div>งานที่ซ่อมกลับมาแล้ว</div>
                    </div>
                </el-button>
                <el-button type="info" @click="ChangeRepairStationStatus('test')">
                    <div class="bilingual-text">
                        <div>标准件上线</div>
                        <div>ชิ้นส่วนมาตรฐาน</div>
                    </div>
                </el-button>

            </div>
        </el-dialog>
        <!-- 物料补漏弹窗 -->
        <el-dialog v-model="supple_materialShowModal" title="物料补料" width="50%" center>
            <!-- 原有内容 -->
            <div>
                工位:
                <el-select v-model="supple_StationCode" placeholder="请选择补料工位" style="width: 150px;">
                    <el-option v-for="station in stateInfo.AllStations" :key="station.StationCode" :value="station.StationCode" :label="station.StationCode"></el-option>
                </el-select>
            </div>
            <span>
                请输入SN：<el-input v-model="supple_SN"></el-input>
            </span>
            <span>
                请输入物料号：<el-input v-model="supple_AssemblySN"></el-input>
            </span>
            <el-popconfirm title="确定补料吗？" @confirm="AddMissedMaterialBindRecord">
                <template #reference>
                    <el-button type="primary">确定</el-button>
                </template>
            </el-popconfirm>
            <!-- <el-button type="primary" @click="BatchApiTest">测试</el-button> -->
            <div>
                <p>{{supple_Log}}</p>
            </div>
        </el-dialog>

        <!-- 不良品管理验证弹窗 -->
        <el-dialog v-model="showModal" title="管理员验证" width="350px" center>
            <template #default>
                <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
                    <el-form-item label="工号" prop="adminId">
                        <el-input v-model="form.adminId" placeholder="请输入工号"></el-input>
                    </el-form-item>

                    <el-form-item label="密码" prop="password">
                        <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                </el-form>
            </template>
            <template #footer>
                <div class="flex justify-between items-center">
                    <el-button type="primary"
                               @click="verifyAdmin">
                        <i class="fa fa-sign-in mr-1"></i>验证
                    </el-button>
                    <el-button type="primary"
                               @click="AddPeopleshowModal = true">
                        <i class="fa fa-plus-circle mr-1"></i>添加确认人
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 添加确认人弹窗 -->
        <el-dialog v-model="AddPeopleshowModal" title="添加确认人" width="50%" center>
            <el-table :data="confirmPeople" style="width: 100%">
                <el-table-column label="工号">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.workerId" placeholder="请输入工号"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="密码">
                    <template #default="{ row, $index }">
                        <el-input type="password"
                                  v-model="row.password"
                                  placeholder="请输入密码"
                                  @input="maskPassword(row, $index)"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="{ $index }">
                        <el-button type="primary" @click="validatePerson($index)">验证</el-button>
                        <el-button type="danger" @click="removePerson($index)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>


            <!-- 添加确认人按钮 -->
            <el-button type="primary" @click="addPerson">添加确认人</el-button>

            <!-- 提交按钮 -->
            <el-button type="success" @click="submit">提交</el-button>

        </el-dialog>

        <!-- 不良品管理弹窗 -->
        <el-dialog v-model="BadProductModal" title="不良品管理" width="90%" center>
            <el-table :data="stateInfo.BadProInfo" style="width: 100%">
                <el-table-column label="产线编码">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.LineCode" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="工位编码">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.StationCode" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="SN">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.SN" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="物料编码">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.MaterialCode" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="物料名称">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.MaterialName" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="不良原因">
                    <template #default="{ row, $index }">
                        <!-- <el-input v-model="row.DefectSource" enable="false"></el-input> -->
                        <el-select v-model="row.DefectSource" filterable allow-create>
                            <el-option value="加工参数异常">加工参数异常</el-option>
                            <el-option value="装配件异常损坏">装配件异常损坏</el-option>
                            <el-option value="其他错误">其他错误</el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="确认人">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.Verifier" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="360">
                    <template #default="{ $index }">
                        <el-popconfirm title="是否已经添加跳站模板？" @confirm="confirmBadproNG($index)">
                            <template #reference>
                                <el-button type="danger">
                                    <div class="bilingual-text">
                                        <div>ยืนยันไม่ผ่าน</div>
                                        <div>确认NG</div>
                                    </div>
                                </el-button>
                            </template>
                        </el-popconfirm>
                        <el-popconfirm title="确认合格放行吗？" @confirm="confirmBadproOK($index)">
                            <template #reference>
                                <el-button type="primary">
                                    <div class="bilingual-text">
                                        <div>ยืนยันผ่าน</div>
                                        <div>确认OK</div>
                                    </div>
                                </el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <el-button type="primary" @click="addBadpro">增加不良品信息</el-button>  
            <el-button type="primary" @click="SkipShowModal=true">添加跳站模板</el-button> -->
        </el-dialog>

        <!-- 批次更换弹窗 -->
        <el-dialog v-model="BatchInfoShowModal" title="批次信息更新" width="90%" center>
            <!-- 原有内容 -->
            <el-table :data="stateInfo.Batchinfos" style="width: 100%">
                <el-table-column label="供应商代码">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.suplierID" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="物料编码">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.materialCode" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="物料名称">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.materialName" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="批次码">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.batchCode" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="余量">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.batchMarginQty" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="单次消耗量">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.batchSingleCostQty" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="添加量">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.batchAddQty" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="更新时间">
                    <template #default="{ row, $index }">
                        <el-input v-model="row.UpdateTime" enable="false"></el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="{ $index }">
                        <el-button type="primary" @click="comfirmBtchinfo($index)">确定</el-button>
                        <el-popconfirm title="确定禁用吗？" @confirm="forbiddeninfo($index)">
                            <template #reference>
                                <el-button type="danger">禁用</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <div>
                <p>{{batchResponse}}</p>
            </div>
            <!-- <el-button type="primary" @click="BatchApiTest">测试</el-button> -->
            <el-button type="primary" @click="addBatch">添加批次信息</el-button>
        </el-dialog>

        <!-- 跳站管理弹窗 -->
        <el-dialog v-model="SkipShowModal" title="跳站选择" width="70%" class="skip-dialog">
            <!-- 原有内容 -->
            <div class="skip_divcontainer">

                <div class="skip_divcontainer_sub1">
                    <header style="height: 35px;">
                        <h1 style="text-align: center;">自定义跳站路线</h1>
                    </header>
                    <el-table :data="SkipOps" style="width: 100%" class="skip_table">
                        <el-table-column label="工序编码">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.OperationCode" enable="false" disabled></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="工序名称">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.OperationName" enable="false" disabled></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否跳站">
                            <template #default="{ row, $index }">
                                <input v-model="row.IsSkip" type="checkbox"></input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="skip_divcontainer_sub1">
                    <el-select v-model="skipmodeltype" placeholder="选择跳站模板" style="width: 250px; height: 35px;" label="模板跳站路线">
                        <el-option v-for="SkipModeType in SkipModeTypes" :key="SkipModeType" :value="SkipModeType" :label="SkipModeType"></el-option>
                    </el-select>
                    <el-table :data="SkipModelOps" style="width: 100%" class="skip_table" v-show="skipmodeltype">
                        <el-table-column label="工序编码">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.OperationCode" enable="false" disabled></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="工序名称">
                            <template #default="{ row, $index }">
                                <el-input v-model="row.OperationName" enable="false" disabled></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否跳站">
                            <template #default="{ row, $index }">
                                <input v-model="row.IsSkip" type="checkbox" disabled></input>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

            </div>
            <div class="skip_divcontainer2">
                <el-button style="background-color: #36ee0c;color: black;" @click="ExecuteSkipByModel">
                    使用模板
                </el-button>
                <el-button style="background-color: #4e69ee;color: black;" @click="ExecuteSkipByCustom">
                    使用自定义
                </el-button>
                <el-button style="background-color: #e9d816;color: black;" @click="SaveSkipModel">
                    保存到模板
                </el-button>
            </div>
        </el-dialog>

        <!-- 电机返修上线 -->
        <el-dialog v-model="TZbackupShowModal" title="电机上线模式" width="60%" center>
            <div class="action-buttons">
                <el-button type="info" @click="ChangeTZStationStatus('normal')">
                    <div class="bilingual-text">
                        <div>正常上线</div>
                        <div>ชิ้นงานปกติ</div>
                    </div>
                </el-button>
                <el-button type="primary" @click="ChangeTZStationStatus('repairbyconfig')">
                    <div class="bilingual-text">
                        <div>自定义返修</div>
                        <div>ซ่อมกำหนดเอง</div>
                    </div>
                </el-button>

                <el-button type="selfconfig" @click="ChangeTZStationStatus('repairbymodel')">
                    <div class="bilingual-text">
                        <div>固定模板返修</div>
                        <div>ซ่อมแม่แบบคงที่</div>
                    </div>
                </el-button>
            </div>
        </el-dialog>
    </el-card>
</template>

<script setup lang="ts" name="过站管理">
    import { ref, reactive, watch, onMounted, getCurrentInstance, defineAsyncComponent, nextTick, computed, onUnmounted } from 'vue';
    import { Console } from 'console';
    import axios from 'axios';
    const ci = getCurrentInstance() as any;
    import { ElMessageBox, ElMessage, ElTable, ElTableColumn } from 'element-plus';
    import { useRouter } from "vue-router";
    import internal from 'stream';
    import other from '/@/utils/other';
    import request from '/@/utils/request';
    import { HubConnectionBuilder } from '@microsoft/signalr';
    import { text } from 'stream/consumers';
    import { isRegExp } from 'util/types';
    import CountdownTimer from '/@/components/ZBZX/CountdownTimer.vue'
    import repair from './repair.vue';

    //过站节拍
    const CycleTime = ref('2.00S');
    const CountDowntimeString = ref("120")

    // 涂胶超时状态
    const glueTimeoutStatus = ref('false');

    // 产线、工位选择信息
    interface SelectedMessage {
        StationCode: null | string;
        LineCode: null | string;
    }
    const selectedMessage = ref<SelectedMessage>({
        StationCode: null,
        LineCode: null,
    });

    // 标志位，表示是否读取到历史选择信息
    const flagValue = ref<number>(0);
    const virtualSN = ref<string | null>(null);
    const StationName = ref('');
    const stationStatus = ref('');

    const sNFlag = ref<number>(0)

    //串口连接状态
    const serialColor = ref('background-color:red;width:30px;height:30px;margin-top:8px')
    const comeinColor = ref('background-color: gray;font-size: 25px;border-radius:50%;padding:10px')
    const port = ref(null);
    const reader = ref(null);

    //

    //串口扫码数据
    const textSN = ref('')
    //扫码结果
    const SNMessage = ref('无扫码信息')
    const alertMessage = ref<string>('')
    const alertMessageJudge = ref<boolean>(true)
    //扫码结果颜色
    const goodmessageColor = ref('background-color:yellow')

    interface IOrder {
        SN: string;
        OrderCode: string;
        ScheduleCode: string;
        MaterialCode: string;
        MaterialName: string; // 使用?表示该属性是可选的
        ScheduleQty: number;
        FinishedCount: number;
    }
    interface BadPro {//不良品信息
        LineCode: string;
        StationCode: string;
        SN: string;
        MaterialCode: string;
        MaterialName: string;
        DefectSource: string;
        Verifier: string;
    }

    interface Dictionary {
        [key: string]: any; // 任何类型的值
    }
    //状态数据
    const stateInfo = reactive({
        //产线信息
        AllLines: [] as any[],
        //工位信息
        AllStations: [] as any[],

        // UI信息
        //工单SN信息
        OrderInfo: [] as IOrder[],  // TAG = 0
        //工位日志信息
        AllLogs: [] as any[],       // TAG = 1
        //工位员工信息
        PersonInfo: [] as any[],     // TAG = 2
        //物料装配信息
        AllMaterial: [] as any[],   // TAG = 3
        //批次信息
        Batchinfos: [] as any[],
        AllBindings: {} as Dictionary,  // TAG = 4
        //不良信息
        BadProInfo: [] as BadPro[],
    });

    //
    const queryType = ref('type1');


    // 接受报错推送信息
    const messages = ref<string[]>([]);
    let connection: signalR.HubConnection | null = null;

    const startConnection = async () => {  //连接服务器
        try {
            connection = new HubConnectionBuilder()
                .withUrl("/NotificationHub")
                //.configureLogging(signalR.LogLevel.Information)
                .withAutomaticReconnect()
                .build();

            connection.on("ReceiveMessage", (message) => {  //注册事件
                if (message.lineCode == selectedMessage.value.LineCode && message.stationCode == selectedMessage.value.StationCode) {

                    flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode);
                    // 如果是涂胶工位，也刷新涂胶状态
                    if (selectedMessage.value.StationCode === '2-OP3250-0') {
                        getGlueTimeoutStatus();
                    }
                }
            });
            await connection.start();
        } catch (err) {
            //console.error("Error starting SignalR connection:", err);
        }
    };

    const stopConnection = () => {
        if (connection) {
            try {
                connection.stop();
            } catch (err) {
            }
        }
    };

    // 页面加载时
    onMounted(() => {
        other.getSelectList('/api/BaseInformation/Station/GetLines', [], false).then(x => { stateInfo.AllLines = x });

        // 获取历史 产线选择
        const lineStorage = localStorage.getItem('selectedLineHistory');
        if (lineStorage) {
            selectedMessage.value.LineCode = lineStorage;
            flagValue.value = 1;
        }
        //创建signalR连接
        startConnection();
    });

    onUnmounted(() => {
        //断开signalR连接
        stopConnection();
    });

    //监听选择产线信息
    watch(() => selectedMessage.value.LineCode, (newValue, oldValue) => {

        request({
            url: '/api/BaseInformation/Station/GetStationsByLine',
            method: 'post',
            data: {
                'LineCode': selectedMessage.value.LineCode
            }
        }).then(res => {
            stateInfo.AllStations = res.Stations.map((x: any) => x);
            //stateInfo.OrderInfo = res.Orders.map((x: any) => x);
        })

        // 获取产线工单信息 tmpordercode= stateTest.MOrder[0].orderCode

        // 保存历史产线选择信息
        if (selectedMessage.value.LineCode != null) {
            localStorage.setItem('selectedLineHistory', selectedMessage.value.LineCode)
        }

        if (flagValue.value == 1) {  // 是读取历史数据
            const StationStorage = localStorage.getItem('selectedStationHistory'); //读取历史工位选择
            const StationNameStorage = localStorage.getItem('selectedStationNameHistory');
            const StationStatusStorage = localStorage.getItem('selectedStationStatusHistory');
            if (StationStorage) {
                selectedMessage.value.StationCode = StationStorage;
                StationName.value = StationNameStorage;
                stationStatus.value = StationStatusStorage;
            }
            //如果是返修工位需要获取其返修状态
            if (selectedMessage.value.StationCode == '2-OP4010-1') {
                GetRepairStationStatus();
            }
            if (selectedMessage.value.StationCode == '2-OP3010-0') {
                GetTZStationStatus();
            }
            // 清空标志位
            flagValue.value = 0;
        } else {
            selectedMessage.value.StationCode = ''
        }
    })



    //监听工位信息
    watch(() => selectedMessage.value.StationCode, (newValue, oldValue) => {
        const thisstation = stateInfo.AllStations.find(info => info.StationCode === newValue);
        if (thisstation) {
            StationName.value = thisstation.StationName;

            if (thisstation.Base_Status == undefined) {
                stationStatus.value = '未启用'
            }
            else if (thisstation.Base_Status == 'USED') {
                stationStatus.value = '启用';
            }
            else
                stationStatus.value = '未启用';
        }
        if (selectedMessage.value.StationCode != null) {
            localStorage.setItem('selectedStationHistory', selectedMessage.value.StationCode);
            localStorage.setItem('selectedStationNameHistory', StationName.value)
            localStorage.setItem('selectedStationStatusHistory', stationStatus.value)
        }
        if (selectedMessage.value.StationCode == '2-OP4010-1') {
            GetRepairStationStatus();
        }
        if (selectedMessage.value.StationCode == '2-OP3010-0') {
            GetTZStationStatus();
        }
        // 获取涂胶超时状态
        if (selectedMessage.value.StationCode == '2-OP3250-0') {
            getGlueTimeoutStatus();
        }
        // 刷新界面信息
        flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode)

    })



    const Snregex = /^DM-TG-.*$/;
    const IsComin = ref(false);

    const flushUI = (lineCode: string | null, stationCode: string | null) => {
        if (lineCode != null && stationCode != null && lineCode != '' && stationCode != '') {

            request({
                url: '/api/BaseInformation/Station/GetUiInfo',
                method: 'post',
                data: {
                    'LineCode': selectedMessage.value.LineCode,
                    'StationCode': selectedMessage.value.StationCode
                }
            }).then(res => {
                if (res.Code == '01') { //无工单信息
                    ClearInfo()
                } else {
                    stateInfo.AllMaterial = res.Materials;  //物料
                    stateInfo.AllBindings = res.Bindings;   //已绑定
                    stateInfo.OrderInfo = res.Orders;   //工单
                    stateInfo.AllLogs = res.Logs;       //工位日志
                    stateInfo.Batchinfos = res.Batchinfos; //批次数据
                    CycleTime.value = res.Cycletime;
                    CountDowntimeString.value = res.GuleApplyCountDown;
                    // console.log('mtname',stateInfo.OrderInfo);
                    if ((stateInfo.OrderInfo.length == 0 ? '' : stateInfo.OrderInfo[0].SN).match(Snregex)) {
                        //console.log("465");
                        comeinColor.value = "background-color: green;font-size: 25px;border-radius:50%;padding:10px";
                        IsComin.value = true;
                    }
                    else {
                        comeinColor.value = "background-color: gray;font-size: 25px;border-radius:50%;padding:10px"
                        IsComin.value = false;
                        animateClass.value = '';
                    }

                }
            })



        } else {
            // 清空界面显示信息
            ClearInfo()
        }
    }

    const ClearInfo = () => {
        stateInfo.PersonInfo = [],  //人员信息
            stateInfo.AllLogs = [],
            stateInfo.AllMaterial = [],
            stateInfo.AllBindings = {},
            stateInfo.OrderInfo = []
    };

    //#region 电机返修上线

    const TZbackupShowModal = ref(false);
    const TZStationStatus = ref('');
    const TZanimateClass = ref('');

    const ChangeTZStationStatus = (status: string) => {
        request({
            url: '/api/BaseInformation/Station/ChangeRepairStationStatus',
            method: 'post',
            data: {
                'configName': 'TZStationStatus',
                'status': status
            }
        }).then(res => {
            if (res.Success == true) {
                ElMessage.success(res.Mesg);
            } else {
                ElMessage.error(res.Mesg);
            }
            GetTZStationStatus();
        })
    }

    const GetTZStationStatus = () => {
        request({
            url: 'api/CustomConfig/Search',
            method: 'post',
            data: {
                'customProperty': 'TZStationStatus'
            }
        }).then(res => {
            // console.log('proval',res.Data[0].propertyValue);
            if (res.Data[0].propertyValue === 'normal') {
                TZStationStatus.value = '正常件';
                TZanimateClass.value = 'TZ-status1'
            }
            else if (res.Data[0].propertyValue === 'repairbyconfig') {
                TZStationStatus.value = '自定义返修';
                TZanimateClass.value = 'TZ-status2'
            }
            else if (res.Data[0].propertyValue === 'repairbymodel') {
                TZStationStatus.value = '固定模板';
                TZanimateClass.value = 'TZ-status3'
            }
            else
                ElMessage.error('返修工位状态值异常：' + res.Data[0].propertyValue);
        })
    }


    //#endregion

    //#region 不良品管理
    //
    // 弹窗状态
    const showModal = ref(false);
    const AddPeopleshowModal = ref(false);
    const BadProductModal = ref(false);
    // 表单数据
    const form = reactive({
        adminId: '',
        password: ''
    });
    // 表单校验规则
    const rules = reactive({
        adminId: [
            { required: true, message: '工号不能为空', trigger: 'blur' },
            // 其他校验规则...
        ],
        password: [
            { required: true, message: '密码不能为空', trigger: 'blur' },
            // 其他校验规则...
        ]
    });
    // 表单引用
    const formRef = ref(null);

    const verifyAdmin = async () => {
        try {
            await formRef.value.validate();
            // 调用校验接口验证工号和密码是否正确
            const isValid = await checkAdminCredentials(form.adminId, form.password);

            if (isValid) {
                //验证成功，进入不良品管理弹窗
                Initbadpro();//初始化不良品信息

                BadProductModal.value = true;
                showModal.value = false;
                //release();
            } else {
                alert('工号或密码错误');
            }
        } catch (error) {
            alert('表单校验失败');
        }
    };

    //初始化 获取当前页面的不良品数据
    const Initbadpro = () => {
        stateInfo.BadProInfo.length = 0; // 清空数组
        stateInfo.BadProInfo.push(
            {
                LineCode: selectedMessage.value.LineCode,
                StationCode: selectedMessage.value.StationCode,
                SN: stateInfo.OrderInfo[0].SN,
                MaterialCode: stateInfo.OrderInfo[0].MaterialCode,
                MaterialName: stateInfo.OrderInfo[0].MaterialName,
                DefectSource: '',//下拉框选项或手动输入
                Verifier: form.adminId,
            });
    };

    //调用接口，确认产品不良
    const confirmBadproNG = (index: any) => {
        const thisBadpro = stateInfo.BadProInfo[index];
        request({
            url: 'api/Record/BadProductRecord/ConfirmNG',
            method: 'post',
            data: {
                'LineCode': thisBadpro.LineCode,
                'StationCode': thisBadpro.StationCode,
                'SnNumber': thisBadpro.SN,
                'MaterialCode': thisBadpro.MaterialCode,
                'MaterialName': thisBadpro.MaterialName,
                'DefectSource': thisBadpro.DefectSource,
                'CreateBy': thisBadpro.Verifier,
            }
        }).then(res => {
            if (res.Success) {
                ElMessage.success(res.Mesg);
            }
            else {
                ElMessage.error(res.Mesg);
            }
            //flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode);
        });
    }
    //确认产品合格
    const confirmBadproOK = (index: any) => {
        const thisBadpro = stateInfo.BadProInfo[index];
        request({
            url: 'api/Record/BadProductRecord/ConfirmOK',
            method: 'post',
            data: {
                'LineCode': thisBadpro.LineCode,
                'StationCode': thisBadpro.StationCode,
                'SnNumber': thisBadpro.SN,
                'MaterialCode': thisBadpro.MaterialCode,
                'MaterialName': thisBadpro.MaterialName,
                'DefectSource': thisBadpro.DefectSource,
                'CreateBy': thisBadpro.Verifier,
            }
        }).then(res => {
            if (res.Success) {
                ElMessage.success(res.Mesg);
            }
            else {
                ElMessage.error(res.Mesg);
            }
            //flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode);
        });
    }


    const releaseDirectly = () => {
        // 执行直接放行逻辑
        release();
        showModal.value = false;
    };

    // 校验接口 验证工号、密码
    async function checkAdminCredentials(id: any, password: any) {
        try {
            const res = await request({ //await 关键字来等待 request 请求的返回值
                url: 'api/Record/BadProductRecord/Check',
                method: 'post',
                data: {
                    'PersonID': id,
                    'PassWord': password,
                }
            });

            if (res.Success) {
                ElMessage.success(res.Mesg);
                return true;  // 返回正确的值
            } else {
                ElMessage.error(res.Mesg);
                return false;
            }
        } catch (error) {
            ElMessage.error('确认人验证失败');
            return false;  // 捕获异常时返回 false
        }
    }

    // 放行逻辑
    function release() {
        // 放行逻辑
        console.log('放行成功');
        showModal.value = false;
    }


    const dialogVisible = ref(false);
    const confirmPeople = ref([]);

    // 打开弹窗
    const openDialog = () => {
        dialogVisible.value = true;
    };

    // 添加确认人
    const addPerson = () => {
        confirmPeople.value.push({ workerId: '', password: '', validated: false });
    };

    // 重置表单
    const resetForm = () => {
        confirmPeople.value = [];
        showModal.value = false;
        AddPeopleshowModal.value = false;
    };

    // 密码掩码处理
    const maskPassword = (row, index) => {
        // 这里不需要做任何处理，因为密码是直接输入的
    };

    // 移除确认人
    const removePerson = (index) => {
        confirmPeople.value.splice(index, 1);
    };

    // 验证单个确认人
    const validatePerson = async (index) => {
        const person = confirmPeople.value[index];
        try {
            // 假设validateAPI是调用身份验证接口的函数
            const result = await validateAPI(person.workerId, person.password);
            if (result.success) {
                ElMessageBox.alert('验证成功', '提示', {
                    confirmButtonText: '确定',
                    type: 'success',
                });
                person.validated = true;
            } else {
                ElMessageBox.alert('验证失败，请重新输入账号密码', '错误', {
                    confirmButtonText: '确定',
                    type: 'error',
                });
            }
        } catch (error) {
            ElMessageBox.alert('验证接口调用失败', '错误', {
                confirmButtonText: '确定',
                type: 'error',
            });
        }
    };

    // 提交所有确认人信息
    const submit = async () => {
        for (const person of confirmPeople.value) {
            if (!person.validated) {
                ElMessageBox.alert('有确认人未验证成功，请重新验证', '提示', {
                    confirmButtonText: '确定',
                    type: 'warning',
                });
                return;
            }
        }
        ElMessageBox.alert('所有确认人验证成功', '提示', {
            confirmButtonText: '确定',
            type: 'success',
        });
        //添加到数据库
        const isValid = await addPeople();
        resetForm();
    };

    //添加确认人信息到数据库
    const addPeople = async () => {
        for (const person of confirmPeople.value) {
            request({
                url: 'api/Record/BadProductRecord/AddPeople',
                method: 'post',
                data: {
                    'PersonID': person.workerId,
                    'PassWord': person.password,
                }
            }).then(res => {
                if (res.Success) {
                    ElMessage.success(res.Mesg);
                    return true;
                }
                else {
                    ElMessage.error(res.Mesg);
                    return false;
                }
            }).catch(error => {
                ElMessage.error('添加确认人' + person.workerId + '失败');
                return false;
            });
        }
    };

    const addBadpro = () => {
        stateInfo.BadProInfo.push({ LineCode: '', StationCode: '', SN: '', MaterialCode: '', MaterialName: '', DefectSource: '', Verifier: '' });
    };


    // 模拟的身份验证API
    const validateAPI = async (workerId, password) => {
        // 这里应该是调用后端API的逻辑
        // 模拟成功或失败
        return { success: true }; // 假设总是成功
    };
    //#endregion

    /****************批次信息处理************************* */

    //#region 批次管理
    const BatchInfoShowModal = ref(false);
    const batchResponse = ref('');

    // 添加批次
    const addBatch = () => {
        stateInfo.Batchinfos.push({ materialCode: '', materialName: '', batchCode: '', batchMarginQty: '', batchSingleCostQty: '', batchAddQty: '', suplierID: '', UpdateTime: '' });
    };

    const comfirmBtchinfo = (index: any) => {
        const thisBatch = stateInfo.Batchinfos[index];
        request({
            url: 'api/BatchCompilations/ManualAddBatch',
            method: 'post',
            data: {
                'lineCode': selectedMessage.value.LineCode,
                'stationCode': selectedMessage.value.StationCode,
                'materialCode': thisBatch.materialCode,
                'batchCode': thisBatch.batchCode,
                'batchAddQty': thisBatch.batchAddQty,
                'batchSingleCostQty': thisBatch.batchSingleCostQty,
                'batchMarginQty': thisBatch.batchMarginQty,
                'suplierID': thisBatch.suplierID,
            }
        }).then(res => {
            if (res.Success) {
                ElMessage.success(res.Mesg);
            }
            else {
                ElMessage.error(res.Mesg);
            }
            //batchResponse.value=res.Mesg;
            flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode);
        });
    }

    const forbiddeninfo = (index: any) => {
        const thisBatch = stateInfo.Batchinfos[index];
        request({
            url: 'api/BatchCompilations/ManualForbiddenBatch',
            method: 'post',
            data: {
                'lineCode': selectedMessage.value.LineCode,
                'stationCode': selectedMessage.value.StationCode,
                'materialCode': thisBatch.materialCode,
                'batchCode': thisBatch.batchCode,
                'suplierID': thisBatch.suplierID,
            }
        }).then(res => {
            if (res.Success) {
                ElMessage.success(res.Mesg);
            }
            else {
                ElMessage.error(res.Mesg);
            }
            //batchResponse.value=res.Mesg;
            flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode);
        });
    }

    const BatchApiTest = async () => {
        request({
            url: 'api/BatchCompilations/GetNewBatch',
            method: 'post',
            data: {
                'lineCode': selectedMessage.value.LineCode,
                'stationCode': selectedMessage.value.StationCode,
                'scanCode': 'P:TH13;M:12348489-00/PCS;B:2337809B;S:ABQTH13247109478184;',   //物料sn
            }
        }).then(res => {
            batchResponse.value = res.Mesg;
        });
    }

    //#endregion

    /******************************************************** */

    /***************************串口管理********************** */
    //#region 串口管理

    //打开串口
    const openPort = async () => {
        try {
            port.value = await navigator.serial.requestPort();
            await port.value.open({ baudRate: 115200 });
        }
        catch (error) {
            alert("打开串口失败：" + error)
        }

        if (port.value && port.value.readable) {

            serialColor.value = "background-color:green;width:30px;height:30px";
        }
        else {
            serialColor.value = "background-color:red;width:30px;height:30px";
        }

        await readPort();
    };

    //关闭串口
    const closePort = () => {

        if (reader.value) {
            reader.value.cancel();
        }

        if (port.value) {
            port.value.close();
        }

        if (port.value && port.value.readable) {
            serialColor.value = "background-color:green;width:30px;height:30px";
        }
        else {
            serialColor.value = "background-color:red;width:30px;height:30px";
        }
    };

    //读取串口
    const readPort = async () => {
        textSN.value = "";
        if (port.value && port.value.readable) {

            reader.value = port.value.readable.getReader();
            try {
                var flag = true
                while (true) {

                    const { value, done } = await reader.value.read();
                    if (done) {
                        textSN.value = value;
                        break;
                    }

                    for (let i = 0; i < value.length; i++) {
                        if (!flag) {
                            flag = true
                            textSN.value = ''
                        }
                        textSN.value += String.fromCharCode(value[i]);
                        if (value[i] === 13) {
                            flag = false
                            // 扫码完成
                            console.log("ss", textSN.value)
                            textSN.value = textSN.value.replace('\r', '').replace('\n', '').trim()

                            virtualSN.value = textSN.value
                            if (selectedMessage.value.LineCode == null || selectedMessage.value.LineCode == '') {
                                SNMessage.value = "无效扫码,请选择产线"
                            }
                            else if (selectedMessage.value.StationCode == null || selectedMessage.value.StationCode == '') {
                                SNMessage.value = "无效扫码,请选择工位"
                            }
                            else if (stateInfo.OrderInfo.length == 0 || stateInfo.OrderInfo[0].SN == null) {
                                SNMessage.value = "当前工位无待绑定SN"
                            }
                            else if (virtualSN.value == '16740221-00' || virtualSN.value == '16725789-00' || virtualSN.value == '16725791-00') {
                                if (virtualSN.value === stateInfo.AllMaterial[0].AssemblyMaterialCode) {
                                    animateClass.value = 'flash-green';
                                    UploadTZCode(virtualSN.value);

                                } else {
                                    animateClass.value = 'flash-red'
                                    ElMessage.error('扫入电机物料编码与当前工单不匹配，请检查');
                                }
                            }
                            else if (BatchInfoShowModal.value === true) {
                                //处理手动扫批次码
                                //console.log("aa",stateInfo.OrderInfo[0].SN)

                                //跟新批次信息
                                request({
                                    url: 'api/BatchCompilations/GetNewBatch',
                                    method: 'post',
                                    data: {
                                        'lineCode': selectedMessage.value.LineCode,
                                        'stationCode': selectedMessage.value.StationCode,
                                        'scanCode': virtualSN.value,
                                    }
                                }).then(res => {
                                    if (res.Success) {
                                        ElMessage.success(res.Mesg);
                                    }
                                    else {
                                        ElMessage.error(res.Mesg);
                                    }
                                    //batchResponse.value=res.Mesg;
                                });
                            }
                            else {

                                if (virtualSN.value != null && virtualSN.value != '') {
                                    request({
                                        url: '/api/BaseInformation/Station/HandleSnNumber',
                                        method: 'post',
                                        data: {
                                            'LineCode': selectedMessage.value.LineCode,
                                            'StationCode': selectedMessage.value.StationCode,
                                            'SnNumber': virtualSN.value,   //物料sn
                                            'OrderCode': stateInfo.OrderInfo[0].SN   //暂时村虚拟SN
                                        }
                                    }).then(res => {
                                        if (res.success == true) {
                                            alertMessageJudge.value = true;
                                        } else {
                                            alertMessageJudge.value = false;
                                        }
                                        alertMessage.value = res.mesg;
                                    })
                                }
                            }
                        }
                    }
                }

            }
            catch (error) {
                console.error(error);
            }
            finally {
                if (reader.value) {
                    reader.value.releaseLock();
                }
            }
        }
    };
    //#endregion
    /******************************************************** */

    //#region 强制出站
    const ForcePassstation = async () => {
        // if( sNFlag.value == 0 ) {
        //     alert("当前工位无待出站工件")
        // } else {
        await request({
            url: '/api/BaseInformation/Station/ForcePassStation',
            method: 'post',
            data: {
                'LineCode': selectedMessage.value.LineCode,
                'StationCode': selectedMessage.value.StationCode,
                'SnNumber': stateInfo.OrderInfo[0].SN,
                'OrderCode': stateInfo.OrderInfo[0].OrderCode
            }
        }).then(res => {
            if (res.success == true) {
                alertMessageJudge.value = true;
            } else {
                alertMessageJudge.value = false;
            }
            alertMessage.value = res.mesg;
        })
        // }
    }
    //#endregion

    //#region 物料信息补漏
    const supple_materialShowModal = ref(false);
    const supple_SN = ref('');
    const supple_AssemblySN = ref('');
    const supple_StationCode = ref('');
    const supple_Log = ref('');
    const AddMissedMaterialBindRecord = async () => {
        // if( sNFlag.value == 0 ) {
        //     alert("当前工位无待出站工件")
        // } else {
        await request({
            url: '/api/BaseInformation/Station/AutoAdd',
            method: 'post',
            data: {
                'lineCode': selectedMessage.value.LineCode,
                'stationCode': supple_StationCode.value,
                'SN': supple_SN.value,
                'AssemblyMaterialSNs': supple_AssemblySN.value
            }
        }).then(res => {
            console.log('supple', res)
            if (res.success == true) {

            } else {
                supple_Log.value = res.mesg
            }
        })
        // }
    }
    //#endregion

    //#region 测试返修上线
    const backUpshowModal = ref(false);
    const RepairStationStatus = ref('');
    const RepairanimateClass = ref('');

    const ChangeRepairStationStatus = (status: string) => {
        request({
            url: '/api/BaseInformation/Station/ChangeRepairStationStatus',
            method: 'post',
            data: {
                'configName': 'BackUpStationStatus',
                'status': status
            }
        }).then(res => {
            if (res.Success == true) {
                ElMessage.success(res.Mesg);
            } else {
                ElMessage.error(res.Mesg);
            }
            GetRepairStationStatus();
        })
    }

    const GetRepairStationStatus = () => {
        request({
            url: 'api/CustomConfig/Search',
            method: 'post',
            data: {
                'customProperty': 'BackUpStationStatus'
            }
        }).then(res => {
            // console.log('proval',res.Data[0].propertyValue);
            if (res.Data[0].propertyValue === 'test') {
                RepairStationStatus.value = '上标准件';
                RepairanimateClass.value = 'repair-status1'
            }
            else if (res.Data[0].propertyValue === 'repair') {
                RepairStationStatus.value = '上返修件';
                RepairanimateClass.value = 'repair-status2'
            }
            else
                ElMessage.error('返修工位状态值异常：' + res.Data[0].propertyValue);
        })
    }


    //#endregion

    /****************************************跳站管理******** */
    //#region 跳站管理
    const SkipShowModal = ref(false);
    const SkipOps = ref([]);
    const SkipModeTypes = ref([]);
    const SkipModelOps = ref([]);
    const skipmodeltype = ref('');
    const SkipModel = ref('');


    watch(() => SkipShowModal.value, (newvalue, oldvalue) => {
        if (newvalue == true && IsComin.value == true) {
            request({
                url: '/api/BaseInformation/RouteOperation/GetOperationByOrder',
                method: 'post',
                data: {
                    'orderCode': stateInfo.OrderInfo[0].OrderCode,
                }
            }).then(res => {
                SkipOps.value = res;
                //console.log('sk',SkipOps.value );
            })
            request({
                url: 'api/SkipOperations/OutSkipModelType',
                method: 'get',
                data: {
                }
            }).then(res => {
                SkipModeTypes.value = res;
                //console.log('sk',SkipOps.value );
            })

        }
        else if (newvalue == true && IsComin.value == false) {
            SkipOps.value = null;
            ElMessage.error("请等托盘进站")
        }

    })

    watch(() => skipmodeltype.value, (newvalue, oldvalue) => {
        request({
            url: 'api/SkipOperations/ShowSkipModel',
            method: 'post',
            data: {
                'modelType': newvalue,
            }
        }).then(res => {
            SkipModelOps.value = (res.length == 0 ? [] : res);
        })
    })

    const SaveSkipModel = () => {
        request({
            url: 'api/SkipOperations/SaveModel',
            method: 'post',
            data: {
                'skipOperations': SkipOps.value,
                'stationCode': selectedMessage.value.StationCode,
            }
        }).then(res => {
            if (res.Success == true) {
                ElMessage.success(res.Mesg)
            }
            else {
                ElMessage.error(res.Mesg);
            }
        })
    }

    const ExecuteSkipByCustom = () => {
        request({
            url: 'api/SkipOperations/ExecuteSkipByCustom',
            method: 'post',
            data: {
                'skipOperations': SkipOps.value,
                'Snnumber': stateInfo.OrderInfo[0].SN
            }
        }).then(res => {
            if (res.Success == true) {
                ElMessage.success(res.Mesg)
            }
            else {
                ElMessage.error(res.Mesg)
            }
        })
    }

    const ExecuteSkipByModel = () => {
        request({
            url: 'api/SkipOperations/ExecuteSkipByModel',
            method: 'post',
            data: {
                'skipOperations': SkipModelOps.value,
                'Snnumber': stateInfo.OrderInfo[0].SN
            }
        }).then(res => {
            if (res.Success == true) {
                ElMessage.success(res.Mesg)
            }
            else {
                ElMessage.error(res.Mesg)
            }
        })
    }
    //#endregion
    /******************************************************* */

    //#region  电机码是否匹配


    // 动画 class 控制
    const animateClass = ref('')
    const UploadTZCode = (TZcode: string) => {
        request({
            url: '/api/BaseInformation/Station/HandleSnNumber',
            method: 'post',
            data: {
                'LineCode': selectedMessage.value.LineCode,
                'StationCode': selectedMessage.value.StationCode,
                'SnNumber': TZcode,   //物料sn
                'OrderCode': stateInfo.OrderInfo[0].SN   //暂时村虚拟SN
            }
        }).then(res => {
            if (res.success == true) {
                alertMessageJudge.value = true;
            } else {
                alertMessageJudge.value = false;
            }
            alertMessage.value = res.mesg;
        })
    }

    //#endregion


    function tableRowClassName({ row }) {
        //const assmeblyCode = stateInfo.AllBindings.value.find(item=>item.AssemblyMaterialCode===row.AssemblyMaterialCode);
        if (stateInfo.AllBindings && stateInfo.AllBindings[row.AssemblyMaterialCode]) {
            return 'success-row'
        }
        //return '';
        return 'common-row'
    }

    //#region 涂胶超时状态管理

    // 获取涂胶超时状态
    const getGlueTimeoutStatus = () => {
        request({
            url: '/api/BaseInformation/Station/GetGlueTimeoutFlag',
            method: 'get'
        }).then(res => {
            glueTimeoutStatus.value = res.Mesg;
            flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode);
        }).catch(error => {
            console.error('获取涂胶超时状态失败:', error);
        });
    }

    // 处理涂胶超时按钮点击
    const handleGlueTimeoutButtonClick = () => {
        if (glueTimeoutStatus.value === 'true') {
            ElMessageBox.confirm('是否手动恢复涂胶超时报警标志位?', '确认', {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning'
            }).then(() => {
                // 用户选择"是"，重置涂胶超时状态
                resetGlueTimeoutStatus();
            }).catch(() => {
                // 用户选择"否"，不执行任何操作
            });
        }
    }

    // 重置涂胶超时状态
    const resetGlueTimeoutStatus = () => {
        request({
            url: '/api/BaseInformation/Station/ResetGlueTimeoutFlag',
            method: 'post'
        }).then(res => {
            if (res.Success) {
                ElMessage.success('涂胶超时状态已重置');
                glueTimeoutStatus.value = 'false';
                flushUI(selectedMessage.value.LineCode, selectedMessage.value.StationCode);
            } else {
                ElMessage.error('重置失败: ' + res.Mesg);
            }
        }).catch(error => {
            ElMessage.error('重置涂胶超时状态失败');
            console.error('重置涂胶超时状态失败:', error);
        });
    }

    //#endregion

    //#region 不良品管理

    //#endregion
</script>

<style>
  .common-row{
      color: #000 !important;
      text-align: center !important;
      background-color:rgb(202, 189, 189) !important;
      width: 100% !important;
  }
  .success-row{
      color: #000 !important;
      text-align: center !important;
      width: 100%;
      background-color:rgb(52, 173, 30) !important;
      
  }
  .table-UI{
      background:#add8e6 !important;
      border: solid !important;
      border-radius: 0.5px;
  }
 </style>

<style scoped lang="scss">


.glue-status-vertical {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 60px;
  margin-left: 10px;
  margin-right: 10px;
}
.glue-status-text {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  font-weight: bold;
}
.glue-status-button {
  width: 60px;
  padding: 0 8px;
}
  
/* 基础工业风格卡片 */
.industrial-card {
  background-color: #eceff2;
  border: 1px solid #6b7a8f;
  border-radius: 4px;
  color: #e0e0e0;
  
  :deep(.el-card__body) {
    padding: 16px;
  }
}

/* 控制面板 - 工业风格 */
.industrial-control-panel {
  background-color: #6487e0;
  border: 1px solid #545e6d;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  
  .selection-label {
    color: #b0b0b0;
    font-weight: 600;
  }
  
  .el-select {
    :deep(.el-input__inner) {
      background-color: #E6F7FF;
      color: #409EFF;
      
      font-weight: bold;
    }
    
    :deep(.el-input__suffix) {
      color: #b0b0b0;
    }
  }
}
  /* 控制区域 */
  .control-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: #F5F7FA;
    border-radius: 8px;
    margin-bottom: 20px;
  }
  
  .selection-area {
    display: flex;
    gap: 30px;
  }
  
  .selection-item {
    display: flex;
    align-items: center;
  }
  
  .selection-label {
    font-weight: bold;
    min-width: 50px;
  }
  
  .selection-input {
    width: 200px;
    margin-right: 15px;
  }
  
  .station-name {
    padding: 5px 10px;
    background: #E6F7FF;
    color: #409EFF;
    border-radius: 4px;
    font-weight: bold;
  }

  
  
  .serial-control {
    display: flex;
    align-items: center;
    gap: 15px;
  }
  
  .status-indicator {
    width: 20px;
    height: 20px;
    border-radius: 50%;
    border: 2px solid white;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  
  /* 扫码区域 */
  .scan-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: #F5F7FA;
    border-radius: 8px;
    margin-bottom: 20px;
  }
  
  .scan-input-group {
    display: flex;
    gap: 30px;
  }
  
  .scan-item {
    margin-bottom: 0;
  }
  
  .scan-input {
    width: 220px;
  }
  
  .cycletime-display {
  width: 120px;
  height: 25px;
  background-color: #e6f5ea;
  border: 3px solid #0e75b6;
  border-radius: 50%;
  color: #0e67e4;
  font-size: 24px;
  font-weight: bold;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  // margin: 20px auto;
}


  .sn-display {
    font-size: 18px;
    font-weight: bold;
    color: #409EFF;
    padding: 8px 15px;
    background: white;
    border-radius: 4px;
    border-left: 4px solid #409EFF;
  }
  
  /* 分割线 */
  .section-divider {
    margin: 25px 0;
  }
  
  /* 功能按钮区域 */
  .action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    justify-content: center;
    margin-bottom: 20px;
  }
  
  .action-button {
    min-width: 140px;
    height: 40px;
  }
  
  /* 工业风格按钮 */
.el-button {
  border-radius: 2px !important;
  font-weight: 600;
  color: #e8ecf4;
  letter-spacing: 0.5px;

  &.el-button--selfconfig {
    background-color: #959211;
    border-color: #e8efbd;
    
    &:hover {
      background-color: #ead306;
    }
  }
  
  &.el-button--primary {
    background-color: #0f55e1;
    border-color: #8a2c2c;
    
    &:hover {
      background-color: #43cfdf;
    }
  }
  
  &.el-button--info {
    background-color: #289d19;
    border-color: #b0b0b0;
    &:hover {
      background-color: #33f009;
    }
  }
  
  &.el-button--danger {
    background-color: #8a2c2c;
    &:hover {
      background-color: #dc1f32;
    }
  }
}

/* 工业风格表格 */
.el-table {
  background-color: #cacbe6 !important;
  border: 1px solid #6b7a8f;
  
  :deep(th) {
    background-color: #3a4a6b !important;
    color: #e0e0e0 !important;
    font-weight: 600;
  }
  
  :deep(tr) {
    background-color: #d5dbe9;
    color: #131212;
    
    &:hover td {
      background-color: #daebef !important;
    }
  }
  
  :deep(.el-table__expanded-cell) {
    background-color: #cbd2de;
  }
}
  /* 工单信息 */
  .order-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    background: #F5F7FA;
    border-radius: 8px;
    margin-bottom: 20px;
  }
  
  .no-order {
    text-align: center;
    width: 100%;
    color: #606266;
  }
  
  .order-details {
    flex: 1;
  }
  
  .order-row {
    display: flex;
    margin-bottom: 10px;
  }
  
  .order-item {
    flex: 1;
    min-width: 250px;
  }
  
  .order-label {
    font-weight: bold;
    color: #0e0e0f;
  }
  
  .order-value {
    color: #0e0e0f;
  }
  
  .status-message {
    padding: 8px 15px;
    border-radius: 4px;
    margin-top: 10px;
    
    &.success {
      background: #F0F9EB;
      color: #67C23A;
    }
    
    &.error {
      background: #FEF0F0;
      color: #F56C6C;
    }
  }
  
  .comein-indicator {
    padding: 10px 20px;
    border-radius: 50px;
    font-size: 18px;
    font-weight: bold;
    color: white;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  /* 主内容区域 */
  .main-content {
    display: flex;
    gap: 20px;
    
  }
  
  .material-table {
    flex: 2;
    background: white;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 12px rgba(9, 193, 199, 0.1);
  }
  
  .log-section {
    flex: 1;
    background: white;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 2px 12px rgba(37, 111, 132, 0.1);
  }
  
  .log-title {
    text-align: center;
    margin-bottom: 15px;
    color: #303133;
  }
  
  .log-container {
    height: 500px;
    overflow-y: auto;
    padding-right: 10px;
  }
  
  .log-item {
    padding: 10px;
    margin-bottom: 8px;
    border-radius: 4px;
    background: #FAFAFA;
    display: flex;
    
  }
  
  .log-time {
    color: #606266;
    margin-right: 10px;
    min-width: 120px;
  }
  
  .log-content {
    flex: 1;
  }
  
  /* 表格行样式 */
  :deep(.el-table .success-row) {
    --el-table-tr-bg-color: #F0F9EB;
  }
  
  :deep(.el-table .common-row) {
    --el-table-tr-bg-color: #FAFAFA;
  }
  
  /* 响应式设计 */
  @media (max-width: 1200px) {
    .main-content {
      flex-direction: column;
    }
    
    .control-section {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
    }
    
    .selection-area {
      flex-direction: column;
      gap: 15px;
      width: 100%;
    }
    
    .selection-input {
      width: 100%;
    }
    
    .scan-section {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start;
    }
    
    .scan-input-group {
      flex-direction: column;
      gap: 15px;
      width: 100%;
    }
    
    .scan-input {
      width: 100%;
    }
    
    .order-row {
      flex-direction: column;
      gap: 10px;
    }
    
    .order-item {
      min-width: 100%;
    }
  }

  .skip-dialog{
    width: 70%;
    //background-color: #36ee0c;
}
.skip_divcontainer { 
    display: flex;  
    align-items: flex-start;
    //justify-content: space-between, left; /* 在元素之间添加等量的空间 */ 
    //margin-right: 50px; 
    width: auto;
    margin-top: 10px;
} 
.skip_divcontainer2 { 
    display: flex;  
    align-items: flex-start;
    //justify-content: space-between, left; /* 在元素之间添加等量的空间 */ 
    //margin-right: 50px; 
    width: auto;
    margin-top: 10px;
    justify-content: flex-end;
    padding: 10px;
}
.skip_divcontainer_sub1 {  //.divcontainer11
    //display: flex;  
    align-items: center;
    //justify-content: space-between, left; /* 在元素之间添加等量的空间 */ 
    width: 100%; 
    margin-left: 10px;
    margin-right: 10px;
    box-shadow: 0px 0px 10px 5px rgba(34, 161, 161, 0.7); /* 黄色发光 */
    padding: 10px;
   
}
.skip_table{
    max-height: 400px;    /* 设置最大高度 */
    overflow-y: auto;     /* 纵向滚动 */
}

.bilingual-text div:first-child {
  margin-bottom: 2px;
}

.value-box {
  font-size: 24px;
  padding: 12px 24px;
  border-radius: 8px;
  transition: background-color 0.3s ease;
  
}

.repair-box{
  display: flex;
  gap: 40px;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中（如果需要垂直居中） */
}

.repair-status1{
  background-color: green;
  color: #f8f8f9;
  width: 120px;
  height: 25px;
  border: 3px solid #0e75b6;
  border-radius: 50%;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  font-weight: bold;
}

.repair-status2{
  background-color: #307bd7;
  color: #f8f8f9;
  width: 120px;
  height: 25px;
  border: 3px solid #0e75b6;
  border-radius: 50%;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  font-weight: bold;
}

.TZ-status1{
  background-color: green;
  color: #f8f8f9;
  width: 120px;
  height: 25px;
  border: 3px solid #0e75b6;
  border-radius: 50%;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  font-weight: bold;
}

.TZ-status2{
  background-color: #307bd7;
  color: #f8f8f9;
  width: 120px;
  height: 25px;
  border: 3px solid #0e75b6;
  border-radius: 50%;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  font-weight: bold;
}

.TZ-status3{
  background-color: #cec21a;
  color: #f8f8f9;
  width: 120px;
  height: 25px;
  border: 3px solid #0e75b6;
  border-radius: 50%;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  font-size: 16px;
  font-weight: bold;
}

.reject-select{
  width: 160px;
  height:30px ;
  margin-right: 10px;
  margin-top: 10px;
  border-radius: 5%;
}

/* 动画效果 */
.flash-green {
  background-color: #d4f4dd;
  color: #2e7d32;
  animation: flash 1s ease-in-out;
}

.flash-red {
  background-color: #fddede;
  color: #c62828;
  animation: flash 1s ease-in-out;
}


@keyframes flash {
  0% {
    transform: translateY(-10px);
    opacity: 0;
  }
  50% {
    transform: translateY(0);
    opacity: 1;
  }
  100% {
    transform: translateY(10px);
    opacity: 0;
  }
}

/* 涂胶状态按钮特殊样式 */
.glue-status-action-button {
  font-weight: bold;
  color: white !important;
  border: none;
  transition: all 0.3s ease;
  
  &.glue-normal {
    background: linear-gradient(45deg, #00ff88, #00cc66) !important;
    border-color: #00aa44 !important;
    box-shadow: 0 2px 8px rgba(0, 255, 136, 0.3);
    
    &:hover {
      background: linear-gradient(45deg, #00ff88, #00dd77) !important;
      box-shadow: 0 4px 12px rgba(0, 255, 136, 0.5);
      transform: translateY(-2px);
    }
  }
  
  &.glue-timeout {
    background: linear-gradient(45deg, #ff0055, #dd0044) !important;
    border-color: #bb0033 !important;
    box-shadow: 0 2px 8px rgba(255, 0, 85, 0.3);
    
    &:hover {
      background: linear-gradient(45deg, #ff0055, #ee0055) !important;
      box-shadow: 0 4px 12px rgba(255, 0, 85, 0.5);
      transform: translateY(-2px);
    }
  }
  
  &:disabled {
    opacity: 0.8;
    cursor: not-allowed;
    transform: none !important;
  }
}

.glue-status-vertical {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-width: 60px;
  margin-left: 10px;
  margin-right: 10px;
}
.glue-status-text {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  font-weight: bold;
}
.glue-status-button {
  width: 60px;
  padding: 0 8px;
}
</style>